package com.xl.rentkeeper.business;

import android.content.SharedPreferences;

import com.squareup.wire.Message;
import com.squareup.wire.Wire;
import com.xl.fuse.protos.packet.AppPlatform;
import com.xl.fuse.protos.packet.Packet;
import com.xl.rentkeeper.App;
import com.xl.rentkeeper.db.orm.DBInterface;
import com.xl.rentkeeper.log.QLog;
import com.xl.rentkeeper.net.INetCallback;
import com.xl.rentkeeper.net.NetEngine;
import com.xl.rentkeeper.net.Request;
import com.xl.fuse.protos.CmdConst;
import com.xl.rentkeeper.util.AndroidUtil;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import okio.ByteString;

/**
 * Created by zwc on 2015/6/24.
 */
public class BaseLogic implements INetCallback,CmdConst{
    App app = App.getApp();
    Wire wire = App.getWire();
    Lock lock = new ReentrantLock();

    static int seq= Math.abs(new Random(System.currentTimeMillis()).nextInt());

    protected void sendReq(long uin,String cmd,Message msg,Object obj) {
        try {
            if (uin > 0 || CMD_USER_LOGIN.equals(cmd)) {
                String pname =App.getApp().getPackageName();
                String versionName = App.getApp().getPackageManager().getPackageInfo(
                        pname, 0).versionName;
                byte[] ebody = SecurityLogic.getInstance().encodeBody(uin, cmd, msg);
                Packet packet = new Packet.Builder().uin(uin).cmd(cmd).seq(seq++)
                        .eBody(ByteString.of(ebody)).imei(AndroidUtil.getIMEI(App.getApp())).platform(AppPlatform.Android).appName(pname).appVer(versionName).build();
                Request req = new Request();
                req.packet = packet;
                req.oriPb = msg;
                req.obj = obj;
                req.callback = this;
                NetEngine.getInstance().sendReq(req);
            } else {
                QLog.d(this,"sendReq not permitted "+uin+" cmd "+cmd);
                App.showToast("not login");
            }

        } catch (Exception e) {
            QLog.d(this, "encode body fail", e);
            return;
        }
    }

    protected void sendReq(String cmd,Message msg,Object obj) {
        sendReq(UserLogic.getInstance().getUid(),cmd,msg,obj);
    }

    @Override
    public void onResp(Request req, Packet resp) {

    }

    public<M extends Message> M getResp(Packet packet,Class<M> messageClass) {
        M resp = null;
        try {
            resp = wire.parseFrom(SecurityLogic.getInstance().decodeEBody(packet),messageClass);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resp;
    }


    public void showToast(String toast) {
        App.showToast(toast);
    }

    public DBInterface getDb() {
        return UserLogic.getInstance().getDBInterface();
    }

    public SharedPreferences getUserSp() {
        return UserLogic.getInstance().getSp();
    }
}
